import axios from 'axios';
import {Message} from 'element-ui';
import router from '../router'
import store from '../store'


//响应拦截器
axios.interceptors.response.use(success => {
  //业务逻辑错误
    if(success.status && success.status === 200) {
      if(success.data.code === 500 || success.data.code === 401) {
        Message.error({message:success.data.message});
        return;
      }else if(success.data.code === 403){
        store.commit('del_token');
        router.replace({
          path: '/login',
          query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
        })
      }
      if(success.data.message){
        Message.success({message: success.data.message});
        if(success.data.message === "操作成功")
        {
          return success.data;
        }
        store.commit('set_token', success.headers["token"]);
        console.log(success.headers);
      }
    }
  return success.data;
},
error => {
    if(error.response.code === 504 || error.response.code === 404){
      Message.error({message: '服务器被吃了！'});
    } else if (error.response.code === 403) {
      Message.error({message: '权限不足，请联系管理员！'});
    } else if (error.response.code === 401 || error.response.code === 500) {
      Message.error({message: '尚未登陆，请登录'});
      // router.replace('/');
      store.commit('del_token');
      router.replace({
        path: '/login',
        query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
      })
      }else{
      if(error.response.data.message){
        Message.error({message:error.response.data.message});
        router.replace({
          path: '/login',
          query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
        })

      }else{
        Message.error({message:'未知错误！'});
      }
    }
    return
});

// 添加请求拦截器
axios.interceptors.request.use(config => {
  // 在发送请求之前做些什么
  //判断是否存在token，如果存在将每个页面header都添加token
  if(store.state.token){
    // config.headers.common['token']=store.state.token
    config.headers.common['Authorization']=store.state.token
  }
  return config;
}, error => {
  // 对请求错误做些什么

  return Promise.reject(error);
});





let base = '';

//传送json格式的post请求
export const postRequest = (url, params) => {
  return axios({
    method: 'post',
    url: '${base}${url}',
    data:params
  })
};


